package com.b2s.scrumblr.kb.service;

import com.b2s.scrumblr.kb.core.redis.RedisOperations;
import com.b2s.scrumblr.kb.core.util.CommonsUtil;
import com.b2s.scrumblr.kb.dao.UserDao;
import com.b2s.scrumblr.kb.model.Role;
import com.b2s.scrumblr.kb.model.User;
import com.b2s.scrumblr.kb.model.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/29.
 */
@Service
public class UserService {

    @Resource
    private UserDao userDao;

    @Resource
    private RedisOperations redisOperations;

    @Cacheable("user")
    public User findUser(User user){
        User result = userDao.findUser(user);
        if(result == null) return null;
        return result;
    }

    @Cacheable("user")
    public User add(User user){
        user.setId(CommonsUtil.getId());

        List<Role> roles = user.getRoles();
        if(CommonsUtil.isNotEmpty(roles)){
            addUserRoles(roles, user.getId());
        }
        userDao.addUser(user);
        return user;
    }

    @CachePut("user")
    public User updateUser(User user){
        List<Role> roles = user.getRoles();
        if(CommonsUtil.isNotEmpty(roles)){
            userDao.deleteUserRoles(user.getId());

            addUserRoles(roles, user.getId());
        }
        userDao.updateUser(user);

        return user;
    }

    public void deleteUser(String username){
        User user = new User();
        user.setUsername(username);
        String cacheKey = CommonsUtil.getCacheKey(this.getClass(), user);
        User cacheUser =(User)redisOperations.get(cacheKey);

        userDao.deleteUserRoles(cacheUser.getId());
        userDao.deleteUser(cacheUser.getId());

        redisOperations.remove(cacheKey);
    }

    private void addUserRoles(List<Role> roles, String uId){
        List<UserRole> userRoles = new ArrayList<UserRole>();
        for(Role role : roles){
            UserRole userRole = new UserRole();
            userRole.setUId(uId);
            userRole.setRId(role.getId());
            userRoles.add(userRole);
        }
        userDao.addUserRoles(userRoles);
    }
}
